package redisKeyDef

import (
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/redis"
)

const DeptSubDefCode = "DeptSubDefCode" //

// DeptSubDef 创建一个新的DeptSubDef
type DeptSubDef struct {
	Redis *redis.Redis
}

// NewDeptSubDef 创建一个新的RedisKeyDef
func NewDeptSubDef(Redis *redis.Redis) *DeptSubDef {
	return &DeptSubDef{
		Redis: Redis,
	}
}

// getKey 获取key
func (l *DeptSubDef) getKey(tenantId int64, userId int64) string {
	return DeptSubDefCode + fmt.Sprintf(":%d:%d", tenantId, userId)
}

// Set 设置
func (l *DeptSubDef) Set(deptIds []int64, tenantId int64, userId int64) error {
	Key := l.getKey(tenantId, userId)
	marshal, err := json.Marshal(deptIds)
	if err != nil {
		return err
	}
	return l.Redis.Set(Key, string(marshal))
}

// Get 获取
func (l *DeptSubDef) Get(tenantId int64, userId int64) ([]int64, error) {
	Key := l.getKey(tenantId, userId)
	get, err := l.Redis.Get(Key)
	if err != nil {
		return nil, err
	}
	var data []int64
	err = json.Unmarshal([]byte(get), &data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// Delete 删除
func (l *DeptSubDef) Delete(tenantId int64, userId int64) error {
	_, err := l.Redis.Del(l.getKey(tenantId, userId))
	if err != nil {
		return err
	}
	return nil
}
